#include <iostream>
// OS
#include <pthread.h>
#include <unistd.h>

pthread_rwlock_t rwlock; // 锁内部会记录有多少读者，当一个读者读完，但还有其它读者正在读时，并不会释放锁，没有读者在读时才释放锁
int data_shared = 0;

void *Reader(void *args)
{
    int in = *(int *)args;
    while (true)
    {
        pthread_rwlock_rdlock(&rwlock);
        pthread_rwlock_unlock(&rwlock);
        std::cout << "I am reader, data_shared is " << data_shared << std::endl; // 读共享数据
        usleep(100000);
    }

    // delete &in; //错，in是局部变量
    delete (int *)args;
    return nullptr;
}
void *Writer(void *args)
{
    int in = *(int *)args;
    while (true)
    {
        pthread_rwlock_wrlock(&rwlock);
        data_shared++; // 修改共享数据
        pthread_rwlock_unlock(&rwlock);
        std::cout << "I am writer, data_shared is " << data_shared << std::endl;
        usleep(100000);
    }

    // delete &in; //错，in是局部变量
    delete (int *)args;
    return nullptr;
}

int main()
{
    pthread_rwlock_init(&rwlock, nullptr);
    const int reader = 2;
    const int writer = 3;
    int total = reader + writer;
    pthread_t tids[total];
    // create thread
    for (size_t i = 0; i < reader; i++)
    {
        int *id = new int(i);
        pthread_create(&tids[i], nullptr, Reader, (void *)id); // id是读者/写者索引
    }
    for (size_t i = reader; i < total; i++)
    {
        int *id = new int(i - reader);
        pthread_create(&tids[i], nullptr, Writer, (void *)id); // id是读者/写者索引
    }
    // jion
    for (size_t i = 0; i < total; i++)
    {
        pthread_join(tids[i], nullptr);
    }
    // 销毁
    pthread_rwlock_destroy(&rwlock);

    return 0;
}